package com.kmist.xiakexing.data;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.kmist.xiakexing.tools.Config;
import com.kmist.xiakexing.utils.MapQyBean;
import com.kmist.xiakexing.utils.scene.MapBean;
import com.kmist.xiakexing.utils.MapExitBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MapDao implements IMapDao{
    private static final String TAG = "MapDao";
    private static final MapDao ourInstance = new MapDao();
    private final XiakexingDBHelper xiakexingDBHelper;
    private SQLiteDatabase db;
    private Cursor c;

    private IMapDaoCallback mCallback = null;
    private static final Map<Integer, MapBean> sCache = new HashMap<>();
    private List<MapExitBean> exits;

    public static MapDao getInstance() {
        return ourInstance;
    }
    private MapDao(){
        xiakexingDBHelper = new XiakexingDBHelper(Config.context);
    }

    @Override
    public void setCallback(IMapDaoCallback callback) {
        this.mCallback = callback;
    }

    @Override
    public MapBean getMap(int mid) {
        MapBean map = null;
        if(mapInCache(mid, map)){
            return map;
        }

        map = getMapBasic(mid);
        if(map == null){
            return null;
        }

        saveMaptoCache(mid, map);
        if (mCallback != null) {
            mCallback.onMapLoaded(map);
        }
        return map;
    }

    @Override
    public void upDatePlayerInfo(int mid, String playerInfo) {
        try {
            db = xiakexingDBHelper.getWritableDatabase();
            String sql = "update map set playerinfo=? WHERE mid=?";
            db.execSQL(sql, new Object[]{playerInfo, mid});
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            db.close();
        }
    }

    @Override
    public MapQyBean getQy(int qyid) {
        MapQyBean mapQyBean = new MapQyBean();
        try {
            db = xiakexingDBHelper.getWritableDatabase();
            String sql = "select * from qy where qyid=?";
            c = db.rawQuery(sql, new String[]{qyid+""});
            if(c.moveToFirst()){
                do{
                    mapQyBean.setQyName(c.getString(c.getColumnIndex("qyname")));
                    mapQyBean.setQyid(c.getInt(c.getColumnIndex("qyid")));
                    mapQyBean.setMid(c.getInt(c.getColumnIndex("mid")));
                }while (c.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            c.close();
            db.close();
        }
        return mapQyBean;
    }

    @Override
    public int getFirstMid() {
        int firstMid = 0;
        try {
            db = xiakexingDBHelper.getWritableDatabase();
            String sql = "select * from gameconfig";
            c = db.rawQuery(sql, new String[]{});
            if(c.moveToFirst()){
                do{
                    firstMid = c.getInt(c.getColumnIndex("firstmid"));
                }while (c.moveToNext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            c.close();
            db.close();
        }
        return firstMid;
    }

    private String getChineseName(String key) {
        String name = "";

        c = db.query(Config.TABLE_NAME_MAP, null, "pname=?", new String[]{key}, null, null,null);
        if(c.moveToFirst()){
            do{
                name = c.getString(c.getColumnIndex("name"));
            }while (c.moveToNext());
            c.close();
        }
        return name;
    }

    /* 获取地图基本信息 */
    private MapBean getMapBasic(int mid) {
        MapBean map = new MapBean();
        try{
            db = xiakexingDBHelper.getReadableDatabase();
            String sql = "SELECT * from map,map_exits WHERE map.id = ? and map_exits.id = ?";
            c = db.rawQuery(sql,new String[]{mid+"", mid+""});
            if(c.moveToFirst()){
                do{
                    map.setId(mid);
                    map.setArea(c.getString(c.getColumnIndex("area")));
                    map.setPname(c.getString(c.getColumnIndex("pname")));
                    map.setName(c.getString(c.getColumnIndex("name")));
                    map.setGid(c.getString(c.getColumnIndex("gid")));
                    map.setNpc(c.getString(c.getColumnIndex("npc")));
                    map.setGtime(c.getString(c.getColumnIndex("mgtime")));
                    map.setMs(c.getInt(c.getColumnIndex("ms")));
                    map.setDesc(c.getString(c.getColumnIndex("desc")));
                    map.setBoss(c.getString(c.getColumnIndex("boss")));
                    map.setQy(c.getInt(c.getColumnIndex("qy")));
                    map.setPlayerInfo(c.getString(c.getColumnIndex("playerinfo")));
                    map.setIsPvp(c.getInt(c.getColumnIndex("ispvp")));

                    List<MapExitBean> mapExitBeans = new ArrayList<>();
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("northwest")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("north")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("northeast")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("up")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("west")),"",""));
                    mapExitBeans.add(new MapExitBean(mid,"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("east")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("down")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("southwest")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("south")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("southeast")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("enter")),"",""));
                    mapExitBeans.add(new MapExitBean(c.getInt(c.getColumnIndex("out")),"",""));
                    map.setMapExits(mapExitBeans);

                }while (c.moveToNext());
                Log.d("MAPDAO", map.toString());
                return map;
            }else{
                if (mCallback != null) {
                    mCallback.onMapLoadEmpty();
                    return null;
                }
            }
        } catch (Exception e) {
            if (mCallback != null) {
                mCallback.onNetWorkError();
            }
            e.printStackTrace();
        }finally {
            db.close();
            c.close();
        }
        return null;
    }

    private boolean mapInCache(int mid, MapBean map) {
        map = sCache.get(mid);
        if(map != null)
        {
            if (mCallback != null) {
                mCallback.onMapLoaded(map);
            }
            return true;
        }
        return false;
    }

    private void saveMaptoCache(int mid, MapBean map) {
        if(sCache.size() > 10)
        {
            Iterator<Integer> i = sCache.keySet().iterator();
            sCache.remove(i.next());
        }
        sCache.put(mid,map);
    }
}


//    private void getMapObjects(MapBean map) {
//        mapObjectBeans = new ArrayList<>();
//        try{
//            db = xiakexingDBHelper.getReadableDatabase();
//            c = db.query(Config.TABLE_NAME_MAP_OBJ, null, "area=? and map=?", new String[]{map.getMapName().getArea(), map.getMapName().getPname()}, null, null,null);
//            if(c.moveToFirst()){
//                do{
//                    mapObjectBeans.add(new MapObjectBean(
//                            c.getString(c.getColumnIndex("type")),
//                            c.getString(c.getColumnIndex("pname")),
//                            "",
//                            c.getInt(c.getColumnIndex("num")),
//                            c.getInt(c.getColumnIndex("random"))
//                    ));
//                }while (c.moveToNext());
//            }
//            map.setMapObjectBeans(mapObjectBeans);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            c.close();
//            db.close();
//        }
//    }

//    private void getMapItems(MapBean map) {
//        itemBeans = new ArrayList<>();
//        try {
//            db = xiakexingDBHelper.getReadableDatabase();
//            c = db.query(Config.TABLE_NAME_MAP_ITEM, null, "area=? and map=?", new String[]{map.getMapName().getArea(), map.getMapName().getPname()}, null, null,null);
//
//            if(c.moveToFirst()){
//                do{
//                    itemBeans.add(new ItemBean(
//                            c.getString(c.getColumnIndex("pname")),
//                            c.getString(c.getColumnIndex("name")),
//                            c.getString(c.getColumnIndex("desc"))
//                    ));
//                }while (c.moveToNext());
//            }
//            map.setItemBeans(itemBeans);
//            c.close();
//        } catch (Exception e) {
//            if (mCallback != null) {
//                mCallback.onNetWorkError();
//            }
//            e.printStackTrace();
//
//        }finally {
//            c.close();
//            db.close();
//        }
//        return;
//    }
